import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';

import 'package:core_package/core_package.dart';
import 'package:flutter/material.dart';
import 'package:flutter_app_unionad/core/socket_manager.dart';
import 'package:flutter_app_unionad/ui/basice/base_navigation_widget.dart';
import 'package:flutter_app_unionad/ui/basice/input_separator_widget.dart';
import 'package:flutter_app_unionad/ui/basice/my_button.dart';
import 'package:flutter_app_unionad/ui/basice/select_title_and_detail_widget.dart';
import 'package:flutter_app_unionad/ui/workbench/widget/select_wifi_widget.dart';

// ignore: must_be_immutable
class UserCenterItem5Page extends StatefulWidget {
  static const String routeName = "/userCenterItem5Page";

  @override
  _UserCenterItem5PageState createState() => _UserCenterItem5PageState();
}

class _UserCenterItem5PageState extends State<UserCenterItem5Page> {
  String? pass;
  String? name;

  @override
  Widget build(BuildContext context) {
    return BaseNavigationWidget(
      title: "增加wifi",
      child: Column(
        children: [
          buildContentWidget(),
          MySizeBox(height: 40),
          MyButton(
            title: "链接",
            onTap: () {
              onTap();
            },
          ),
        ],
      ),
    );
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
  }

  void sendParams(int length) async {
    ProgressDialog.showPayFirstLoading(context, msg: '链接中...\n请勿中断');
    // ignore: close_sinks
    final socket = await Socket.connect('192.168.4.1', 9080);
    if (socket == null) {
      ShowToastWidget.showToast(msg: "链接失败，请到把手机链接wifi \'niuniulife\'");

      return;
    }
    await Future.delayed(Duration(seconds: 5));

    socket.listen((List<int> event) async {
      print('222');

      print(utf8.decode(event));
      socket.add(utf8.encode('FFFFFFFE${length}AT+CWJAP="$name","$pass"'));
      await Future.delayed(Duration(seconds: 5));
      socket.close();
      Navigator.pop(context);
      ShowToastWidget.showToast(msg: "链接成功");
    });

    // send hello
    socket.add(utf8.encode('FFFFFFFF${length}AT+CWJAP="$name","$pass"'));
  }

  void onTap() async {
    // name = '共享联系Q421626363';
    // pass = 'hzj19930926';
    if (name == null || name!.stringIsEmpty) {
      ShowToastWidget.showToast(msg: '请输入Wifi名称');
      return;
    }
    if (pass == null || pass!.stringIsEmpty) {
      ShowToastWidget.showToast(msg: '请输入Wifi密码');
      return;
    }
    String str = 'AT+CWJAP="$name","$pass"';
    int count = 0;
    for (int i = 0; i < str.length; i++) {
      if (str[i].codeUnits.first > 127) {
        count += 1;
      }
    }
    int length = str.length + count * 2;

    print('开始建立链接');
    sendParams(length);
  }

  Widget buildContentWidget() {
    return Container(
      padding: EdgeInsets.only(left: 35.px, right: 30.px),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(5.px),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          MySizeBox(height: 50),
          Text(
            "增加wifi",
            style: TextStyle(
              color: MyColors.color_27_27_27,
              fontSize: MyFont.font16,
              fontWeight: MyFontWeight.bold,
            ),
          ),
          MySizeBox(height: 30),
          SelectTitleAndDetailWidget(
            title: "",
            detail: "请将手机连接到路由设备niuniulife",
            // detailStyle: TextStyle(
            //   color: MyColors.color_246_45_29,
            //   fontWeight: MyFontWeight.regular,
            //   fontSize: MyFont.font14,
            // ),
            titleWidth: 0.px,
            // icon: Icon(
            //   Icons.arrow_drop_down,
            //   size: 15.px,
            // ),
          ),
          MySizeBox(height: 20),
          Platform.isIOS
              ?
          InputSeparatorWidget(
            valueChange: (value) {
              name = value;
            },
            title: "Wifi名称",
            placeholder: "请输入路家用Wifi名称",
            titleWidth: 100.px,
          )
          : SelectTitleAndDetailWidget(
              title: "Wifi名称",
              detail: name != null ? name : "请选择WiFi",
              titleWidth: 100.px,
              onTap: () {
                SelectWifWidget.show(context).then((value) {
                  if (value != null) {
                    name = value;
                    if (mounted) setState(() {});
                  }
                });
              },
              icon: Icon(
                Icons.arrow_drop_down,
                size: 15.px,
              ),
            )
          ,
          MySizeBox(height: 10),
          InputSeparatorWidget(
            valueChange: (value) {
              pass = value;
            },
            title: "Wifi密码",
            placeholder: "请输入Wifi密码",
            titleWidth: 100.px,
          ),
          MySizeBox(height: 30),
        ],
      ),
    );
  }
}
